// pages/mapInfo/mapInfo.js
var amapFile = require('../../libs/amap-wx.js'); //如：..­/..­/libs/amap-wx.js
var MapContext;
var myAmapFun;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    myAmapFun = new amapFile.AMapWX({
      key: '8c35377618798a4b8c8228591712766b'
    });
    let tips = JSON.parse(decodeURIComponent(options.tips))
    let selfAddress = JSON.parse(decodeURIComponent(options.selfAddress))
    console.log(tips)
    console.log(selfAddress)
    this.setData({
      tips: tips,
      selfAddress: selfAddress
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    MapContext = wx.createMapContext('map')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 获取我的位置
  getMyMap(e) {
    let that = this
    //自行查询经纬度 http://www.gpsspg.com/maps.htm
    let selfAddress = that.data.selfAddress
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        let latitude = res.latitude
        let longitude = res.longitude
        // console.log('latitude:' + latitude)
        // console.log('longitude:' + longitude)
        MapContext.moveToLocation({
          longitude: longitude,
          latitude: latitude,
        })
        that.setData({
          latitude: latitude,
          longitude: longitude
        })
        myAmapFun.getRegeo({
          success: (res) => {
            console.log(res[0].regeocodeData.formatted_address)
            selfAddress.address = res[0].regeocodeData.formatted_address
            that.setData({
              selfAddress: selfAddress
            })
          }
        })
      }
    })
  },
  chooseAddress(e){
    let textData = this.data.tips.filter(item => item.id == e.currentTarget.dataset.id)
    let pages = getCurrentPages(); // 当前页面
    let beforePage = pages[pages.length - 2];
    // console.log(textData[0].latitude)
    // console.log(textData[0].longitude)
    wx.navigateBack({
      delta: 1,
      success: function () {
        beforePage.setData({
          textData: {
            name: textData[0].name,
            desc: textData[0].address,
          }
        })
        beforePage.makertap({ markerId:e.currentTarget.dataset.id},{
          latitude: textData[0].latitude,
          longitude: textData[0].longitude,
        })
      }
    });
  }
})